<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="司机数据"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <!-- <el-button type="primary" :icon="Refresh" @click="refreshTable">
          刷新数据
        </el-button>-->
        <!-- <el-button type="success" :icon="Download" plain @click="exportData" :disabled="!scope.isSelected">
          导出选中
        </el-button> -->
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link :icon="EditPen" @click="openEdit(row)">
          编辑
        </el-button>
        <el-button type="primary" link :icon="View" @click="viewDriver(row)">
          查看
        </el-button>
        <!-- <el-button type="success" link :icon="Phone" @click="contactDriver(row)">
          联系
        </el-button> -->
      </template>
    </ProTable>
    <DriverEdit ref="driverEditRef" />
    <VehicleDetail ref="vehicleDetailRef" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Download, View, Phone, EditPen } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import DriverEdit from '@/views/datalist/driverData/components/DriverEdit.vue';
import VehicleDetail from '@/views/datalist/driverData/components/VehicleDetail.vue';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import { getDriverUserList, editUser } from '@/api/modules/datainfo/driverUser';
import type { UserQuery, UserInfo } from '@/api/types/datainfo/driverUser';
import { useHandleData } from '@/hooks/useHandleData';

defineOptions({
  name: 'datalistDriver'
});
const proTableRef = ref<ProTableInstance>();
const driverEditRef = ref<InstanceType<typeof DriverEdit>>();
const vehicleDetailRef = ref<InstanceType<typeof VehicleDetail>>();

// 表格列配置
const columns: ColumnProps<UserInfo>[] = [
  { type: 'selection', width: 80 },
  { type: 'index', label: '序号', width: 80 },
  { prop: 'username', label: '用户名', width: 150 },
  { prop: 'nickname', label: '昵称', width: 150 },
  { prop: 'phone', label: '手机号', width: 200 },
  { prop: 'idCard', label: '身份证', width: 180 },
  { prop: 'age', label: '年龄', width: 100 },
  { prop: 'email', label: '邮箱', width: 180 },
  { prop: 'sex', label: '性别', width: 80, render: (scope) => {
    const sex = scope.row.sex;
    if (sex === 1 || sex === '1') return '男';
    if (sex === 2 || sex === '2') return '女';
    return '未知';
  }},
  // { prop: 'roleName', label: '角色', width: 100 },
  // { prop: 'accountStatusCd', label: '账户状态', width: 100, tag: true, render: (scope) => {
  //   const status = scope.row.accountStatusCd;
  //   // 根据返回的数据，状态码为 1000001，可能表示正常状态
  //   return status === '1000001' ? '正常' : status === '1000002' ? '锁定' : status === '1000003' ? '禁用' : '未知';
  // }},
  { prop: 'createTime', label: '创建时间' },
  // { prop: 'lastLoginTime', label: '最后登录时间', width: 180, render: (scope) => {
  //   return scope.row.lastLoginTime || '从未登录';
  // }},
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
];
// 搜索条件项
const searchColumns: SearchProps[] = [
  { prop: 'username', label: '用户名', el: 'input' },
  { prop: 'nickname', label: '昵称', el: 'input' },
  { prop: 'phone', label: '手机号', el: 'input' },
  { prop: 'idCard', label: '身份证', el: 'input' },
  // {
  //   prop: 'accountStatusCd',
  //   label: '账户状态',
  //   el: 'select',
  //   enum: [
  //     { label: '正常', value: '1000001' },
  //     { label: '锁定', value: '1000002' },
  //     { label: '禁用', value: '1000003' }
  //   ],
  //   fieldNames: { label: 'label', value: 'value' }
  // },
  {
    prop: 'createTime',
    label: '创建时间',
    el: 'date-picker',
    span: 2,
    props: {
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      format: 'YYYY-MM-DD HH:mm:ss'
    }
  }
];
// 获取table列表
const getTableList = (params: UserQuery) => {
  const newParams = formatParams(params);
  return getDriverUserList(newParams);
};

// 格式化参数
const formatParams = (params: UserQuery) => {
  const newParams = JSON.parse(JSON.stringify(params));
  
  // 处理创建时间范围
  if (newParams.createTime && Array.isArray(newParams.createTime)) {
    newParams.startDate = newParams.createTime[0];
    newParams.endDate = newParams.createTime[1];
    delete newParams.createTime;
  }
  
  return newParams;
};

// 刷新表格数据
const refreshTable = () => {
  proTableRef.value?.getTableList();
  ElMessage.success('数据刷新成功');
};

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能待实现...');
};

// 打开编辑对话框
const openEdit = async (row: UserInfo) => {
  try {
    // 获取用户详情（如果需要的话）
    const params = {
      title: '编辑司机信息',
      row: { ...row },
      api: editUser,
      getTableList: proTableRef.value?.getTableList
    };
    driverEditRef.value?.acceptParams(params);
  } catch (error) {
    console.error('Open edit dialog error:', error);
    ElMessage.error('打开编辑对话框失败');
  }
};

// 查看司机详情 - 跳转到车辆详情页
const viewDriver = (row: UserInfo) => {
  try {
    // 传递司机ID和司机信息
    vehicleDetailRef.value?.acceptParams(row, row.id);
  } catch (error) {
    console.error('Open vehicle detail dialog error:', error);
    ElMessage.error('打开车辆详情失败');
  }
};

// 联系司机
const contactDriver = (row: UserInfo) => {
  if (!row.phone) {
    ElMessage.warning('该司机没有留手机号');
    return;
  }
  
  ElMessageBox.confirm(
    `是否要拨打司机 ${row.nickname || row.username} 的电话：${row.phone}？`,
    '联系司机',
    {
      confirmButtonText: '拨打电话',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 在实际项目中，这里可以集成电话功能或者复制到剪贴板
    navigator.clipboard?.writeText(row.phone).then(() => {
      ElMessage.success('电话号码已复制到剪贴板');
    }).catch(() => {
      ElMessage.info(`司机电话：${row.phone}`);
    });
  }).catch(() => {
    // 用户取消
  });
};
</script>
